package com.example.democrud.user;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.democrud.common.exception.DBCreateException;
import com.example.democrud.user.dao.UserMapper;
import com.example.democrud.user.pojo.UserDO;
import com.example.democrud.user.pojo.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.WebApplicationContext;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yml
 * @since 2020-04-26
 */
@Service
//@Scope(value = WebApplicationContext.SCOPE_SESSION,proxyMode = ScopedProxyMode.TARGET_CLASS) 会话bean 
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    private  final UserMapper userMapper;
    public UserServiceImpl (UserMapper  userMapper){
        this.userMapper = userMapper;
    }
    @Override
    public Long create(UserDTO userDTO) {
        String password=DigestUtils.md5DigestAsHex((userDTO.getName()+userDTO.getPassword()).getBytes());
        userDTO.setPassword(password);
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userDTO,userDO);
        if(!save(userDO))
            throw new DBCreateException();
        return userDO.getId();
    }

    @Override
    public UserDO retrieve(Long id) {
        UserDO userDO=getById(id);
        //密码置为空
        userDO.setPassword("");
        return userDO;
    }

    @Override
    public UserDO retrieve(UserDTO userDTO) {
        userDTO.setPassword(DigestUtils.md5DigestAsHex((userDTO.getName()+userDTO.getPassword()).getBytes()));
        UserDO one = new LambdaQueryChainWrapper<UserDO>(userMapper).eq(UserDO::getName, userDTO.getName())
                .eq(UserDO::getPassword, userDTO.getPassword()).one();
        if(one!=null) one.setPassword("");
        return one;
    }

    @Override
    public UserDO delete(Long id) {
        return delete(id);
    }

    public static void main(String[] args) {
        String name = "admin";
        String password = "admin";

        System.out.println(DigestUtils.md5DigestAsHex((name+password).getBytes()));
    }



}
